<template>
	<view class="container">
		<view class="main">
			<u--form :model="registerForm" :rules="rules" ref="form">
				<u-form-item prop="username" borderBottom>
					<u--input v-model="registerForm.username" clearable border="none"
						:placeholder="$tt('register.inputUserName')" prefixIcon="account-fill"
						prefixIconStyle="font-size: 44rpx; color: #486FF2; margin-right: 10rpx"></u--input>
				</u-form-item>
				<u-form-item prop="phonenumber" borderBottom>
					<u--input v-model="registerForm.phonenumber" clearable border="none"
						:placeholder="$tt('register.inputPhone')" prefixIcon="phone-fill"
						prefixIconStyle="font-size: 44rpx; color: #486FF2; margin-right: 10rpx"></u--input>
				</u-form-item>
				<u-form-item prop="password" borderBottom>
					<u--input v-model="registerForm.password" type="password" clearable border="none"
						:placeholder="$tt('register.inputPassword')" prefixIcon="lock-fill"
						prefixIconStyle="font-size: 44rpx; color: #486FF2; margin-right: 10rpx"></u--input>
				</u-form-item>
				<u-form-item prop="confirmPassword" borderBottom>
					<u--input v-model="registerForm.confirmPassword" type="password" clearable border="none"
						:placeholder="$tt('register.inputPasswordAgain')" prefixIcon="lock-fill"
						prefixIconStyle="font-size: 44rpx; color: #486FF2; margin-right: 10rpx"></u--input>
				</u-form-item>
				<u-form-item prop="code" borderBottom>
					<!-- 注意：由于兼容性差异，如果需要使用前后插槽，nvue下需使用u--input，非nvue下需使用u-input -->
					<u-input :placeholder="$tt('register.inputCode')" v-model="registerForm.code" border="none"
						prefixIcon="integral-fill"
						prefixIconStyle="font-size: 44rpx; color: #486FF2; margin-right: 10rpx">
						<template slot="suffix">
							<u--image :src="codeUrl" width="120px" height="30px" @click="getCode"></u--image>
						</template>
					</u-input>
				</u-form-item>
				<view class="clause-wrap">
					<view class="clause">
						<u-checkbox-group @change="handleClauseCheckbox">
							<label>
								<u-checkbox :checked="isClause" style="transform:scale(0.8)" />
							</label>
							<text class="check_text">
								<text>{{$tt('bindRegister.policy0')}}</text>
								<text class="link" @click="handleGoToPrivacy">{{$tt('bindRegister.policy1')}}</text>
								<text class="link" @click="handleGoToService">{{$tt('bindRegister.policy2')}}</text>
								<text class="link" @click="handleGoToStatement">{{$tt('bindRegister.policy3')}}</text>
								<text class="link" @click="handleGoToCommonBill">{{$tt('bindRegister.policy4')}}</text>
							</text>
						</u-checkbox-group>
					</view>
				</view>
				<view style="margin-top:40rpx;">
					<u-button style="height: 90rpx; width: 650rpx;" type="primary" shape="circle"
						:text="$tt('bindRegister.bindRegister')" @click="handleRegister()"></u-button>
				</view>
			</u--form>
		</view>
	</view>
</template>

<script>
	import projectConfig from '@/env.config.js';
	import { captchaImage, bindRegister, getProfile } from '@/apis/modules/common.js';

	export default {
		data () {
			return {
				isClause: false,
				codeUrl: '',
				registerForm: {
					username: '',
					phonenumber: '',
					password: '',
					confirmPassword: '',
					code: '',
					uuid: '',
					bindId: ''
				},
				rules: {
					username: {
						type: 'string',
						min: 4,
						max: 20,
						required: true,
						message: this.$tt('register.inputUserNameSize'),
						trigger: ['blur', 'change']
					},
					phonenumber: [{
							type: 'integer',
							min: 11,
							max: 11,
							required: true,
							message: this.$tt('register.inputPhone'),
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: this.$tt('bindRegister.incorrectPhone'),
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur']
						}
					],
					password: {
						type: 'string',
						required: true,
						min: 5,
						max: 20,
						message: this.$tt('bindRegister.inputPasswordSize'),
						trigger: ['blur', 'change']
					},
					confirmPassword: [{
							type: 'string',
							required: true,
							message: this.$tt('register.inputPassword'),
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								if (this.registerForm.password !== value) {
									// uni.$u.test.mobile()就是返回true或者false的
									return false;
								} else {
									return true;
								}
							},
							message: this.$tt('bindRegister.enterPasswordsDiffer'),
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur']
						}
					],
					code: {
						type: 'integer',
						required: true,
						message: this.$tt('register.inputCode'),
						trigger: ['blur', 'change']
					}
				}
			};
		},
		onLoad (option) {
			//在加载时获取跳转后的数据
			this.registerForm.bindId = option.bindId;
			this.getCode();
		},
		methods: {
			// 获取验证码
			getCode () {
				captchaImage(true).then(res => {
					this.codeUrl = 'data:image/gif;base64,' + res.img;
					this.registerForm.uuid = res.uuid;
					this.registerForm.code = "";
				})
			},
			// 用户注册
			handleRegister () {
				this.$refs.form.validate().then(res => {
					if (!this.isClause) {
						uni.showToast({
							icon: 'none',
							title: this.$tt('login.readAndCheckTheAgreement'),
						});
						return;
					}
					// 调用注册绑定接口
					bindRegister(this.registerForm).then(async res => {
						if (res.code === 200) {
							// 存储token和账号
							this.saveToken(res.token);
							this.saveAccount();
							// 获取用户信息
							let profile = await this.getProfile();
							uni.$u.vuex('profile', profile);
							// 跳转主页
							uni.switchTab({
								url: '/pages/tabBar/home/index'
							});
						} else {
							if (res.msg) {
								uni.showToast({
									icon: "none",
									title: res.msg,
									complete: (res) => {
										setTimeout(() => {
											this.getCode();
										}, 1500);
									}
								})
							}
						}
					})
				})
			},
			// 获取用户信息
			getProfile () {
				return new Promise((resolve, reject) => {
					getProfile().then(res => {
						resolve(res.data);
					}).catch(err => {
						this.$u.toast(err.msg);
					})
				});
			},
			saveToken (token) {
				uni.setStorageSync('token', token); // 本地缓存存储token
				uni.$u.vuex('vuex_token', token); // vuex存储token
			},
			saveAccount () {
				// 本地缓存存储
				uni.setStorageSync('username', this.registerForm.username);
				uni.setStorageSync('password', this.registerForm.password);
			},
			// 隐私政策
			handleGoToPrivacy () {
				let title = this.$tt('login.privacyPolicy');
				let url = projectConfig.OFFICIAL_WEB_URL + 'privacy-policy.html';
				uni.navigateTo({
					url: `/pages/common/webview/index?title=${title}&url=${url}`
				});
			},
			// 服务协议
			handleGoToService () {
				let title = this.$tt('login.serviceAgreement');
				let url = projectConfig.OFFICIAL_WEB_URL + 'service-agreement.html';
				uni.navigateTo({
					url: `/pages/common/webview/index?title=${title}&url=${url}`
				});
			},
			// 儿童隐私保护声明
			handleGoToStatement () {
				let title = this.$tt('login.childProtectionStatement');
				let url = projectConfig.OFFICIAL_WEB_URL + 'child-protection-statement.html';
				uni.navigateTo({
					url: `/pages/common/webview/index?title=${title}&url=${url}`
				});
			},
			// 第三方信息共享清单
			handleGoToCommonBill () {
				let title = this.$tt('login.commonBill');
				let url = projectConfig.OFFICIAL_WEB_URL + 'common-bill.html';
				uni.navigateTo({
					url: `/pages/common/webview/index?title=${title}&url=${url}`
				});
			},
			// 勾选协议
			handleClauseCheckbox (e) {
				this.isClause = !this.isClause;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.main {
		padding: 20px;
		background: #ffffff;
		border-top-left-radius: 0px;
		border-top-right-radius: 0px;

		.clause-wrap {
			margin: 40rpx 0;

			.clause {
				font-size: 28rpx;

				.check_text {}

				.link {
					color: #486FF2;
				}
			}
		}
	}
</style>